﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;

namespace NetworkServerTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        Socket client;
        IPEndPoint clientep;
        Socket newsock;
        private void Form1_Load(object sender, EventArgs e)
        {
            /*
            while (true)
            {
                data = new byte[1024];
                recv = client.Receive(data);
                if (recv == 0)
                    break;

                textBox1.Text += Encoding.ASCII.GetString(data, 0, recv);

                client.Send(data, recv, SocketFlags.None);
            }
            */
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any,
                        9050);
            newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            newsock.Bind(ipep);
            newsock.Listen(10);

            textBox1.Text += "Waiting for a client...";
            this.Update();
            this.Invalidate();
            this.Refresh();
            client = newsock.Accept();
            clientep = (IPEndPoint)client.RemoteEndPoint;
            textBox1.Text += "Connected with " + clientep.Address + "at port " + clientep.Port;
            this.Update();
            this.Invalidate();
            this.Refresh();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            byte[] data = new byte[1024];
            string welcome = "Welcome to my test server";
            data = Encoding.ASCII.GetBytes(welcome);
            client.Send(data, data.Length, SocketFlags.None);
        }

        private void button4_Click(object sender, EventArgs e)
        {
            textBox1.Text += "Disconnected from " + clientep.Address;
            client.Close();
            newsock.Close();
        }
    }
}
